#include "Viewport.h"
class Viewport_Cleaner {
public:
    ~Viewport_Cleaner() {
        Viewport::destroy();
    }
}  Viewport_Cleaner_instance;

Viewport *Viewport::instance = NULL;

bool Viewport::keep_looping = true;

Viewport::Viewport(int _width, int _height, int _bits_per_pixel, Uint32 flags,
        unsigned short int _refresh_rate) {
    if(instance) {
        throw runtime_error("Viewport::Viewport() - reinstantiation of singleton class");
    }
    if (SDL_Init(SDL_INIT_VIDEO) != 0) {
        throw runtime_error("Viewport::Viewport() - Could not initialize Viewport."
                "   Description: " + std::string(SDL_GetError()));
    }

    atexit(SDL_Quit);
    surface = SDL_SetVideoMode(_width, _height, _bits_per_pixel, flags);
    if (surface == NULL) {
        throw runtime_error("Viewport::init() - Could not initialize Viewport."
                "   Description: " + std::string(SDL_GetError()));
    }

    colorkey = SDL_MapRGB(surface->format, 0, 0, 255);
    width = surface->w;
    height = surface->h;
    bits_per_pixel = _bits_per_pixel;
    refresh_rate = _refresh_rate;
    instance = this;

    wx = wy = 0;
    keep_looping = true;
    response_rate = 15;
    if (Debug::test(DEBUG_CREATE_DELETE)) {
        cout << "viewport created" << endl;
    }
}

Viewport::~Viewport() {
    SDL_FreeSurface(surface);
    instance = NULL;
}

void Viewport::update() {
    SDL_Flip(surface);
//    SDL_UpdateRect(surface, 0, 0, 0, 0);
    if (Debug::test(DEBUG_RENDER)) {
        cout << "updated viewport" << endl;
    }
}

void Viewport::increment_wx(int inc_val) {
    if (Debug::test(DEBUG_INFO)) {
        cout << "x incremented" << endl;
    }
    wx += inc_val;
}

void Viewport::increment_wy(int inc_val) {
    if (Debug::test(DEBUG_INFO)) {
        cout << "y incremented" << inc_val << endl;
    }
    wy += inc_val;
}

void Viewport::decrement_wx(int dec_val) {
    if (Debug::test(DEBUG_INFO)) {
        cout << "x decremented" << endl;
    }
    wx -= dec_val;
}

void Viewport::decrement_wy(int dec_val) {
    if (Debug::test(DEBUG_INFO)) {
        cout << "y decremented" << endl;
    }
    wy -= dec_val;
}

Viewport *Viewport::get_instance() {
    if(!instance) {
        throw runtime_error("Viewport::get_instance() - Viewport not created yet");
    }
    return instance;
}

void Viewport::destroy() {
    if(instance) {
        delete instance;
        instance = NULL;
        if (Debug::test(DEBUG_INFO)) {
            cout << "Viewport destroyed" << endl;
        }
    }
}
